package com.frxuexi.mdm2206.myview

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.navigation.NavHostController
import com.frxuexi.lib_base.RoutePath
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.runBlocking

class MyProgressView:View {
    lateinit var paint_hu: Paint
    lateinit var paint_tx:Paint
    lateinit var navHostController:NavHostController
    constructor(context: Context?,navHostController: NavHostController) : super(context){
        initPaint()
        this.navHostController=navHostController
    }
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs){
        initPaint()
    }
    var progress=0f
    var time=5

    fun initPaint(){
        paint_hu=Paint()
        paint_hu.color=Color.GRAY
        paint_hu.strokeWidth=5f
        paint_hu.style=Paint.Style.STROKE


        paint_tx= Paint()
        paint_tx.color=Color.RED
        paint_tx.textSize=30f

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawArc(50f,50f,250f,250f,0f,progress,false,paint_hu)
        canvas.drawText("$time",145f,150f,paint_tx)
    }

    fun start(){
        runBlocking{
            val animator = ValueAnimator.ofFloat(0f, 360f)
            animator.addUpdateListener {
                progress=it.animatedValue as Float
                invalidate()//重绘
            }
            animator.setDuration(time*1000L)
            animator.start()
        }

        runBlocking {
            val animator = ValueAnimator.ofInt(time, 1)
            animator.addUpdateListener {
                time=it.animatedValue as Int
                invalidate()//重绘
                if(time==1){
                    //存值
                    MMKV.defaultMMKV().encode("isIn",true)
                    navHostController.navigate(RoutePath.MAIN)
                }
            }
            animator.setDuration(time*1000L)
            animator.start()
        }
    }
}